import urllib3
import json

def http_delete(url, data, token):
    http = urllib3.PoolManager()
    headers = {'Content-Type': 'application/json', 'token-rxd': token}
    encoded_data = json.dumps(data).encode('utf-8')
    r = http.request('DELETE', url, body=encoded_data, headers=headers)
    status = json.loads(r.data.decode('utf-8'))['code']
    if status != 200:
        print("HTTP DELETE FAIL: " + str(json.loads(r.data.decode('utf-8'))))
        return None
    ret = json.loads(r.data.decode('utf-8'))
    return ret


def http_put(url, data, token):
    http = urllib3.PoolManager()
    headers = {'Content-Type': 'application/json', 'token-rxd': token}
    encoded_data = json.dumps(data).encode('utf-8')
    r = http.request('PUT', url, body=encoded_data, headers=headers)
    status = json.loads(r.data.decode('utf-8'))['code']
    if status != 200:
        print("HTTP PUT FAIL: " + str(json.loads(r.data.decode('utf-8'))))
        return None
    ret = json.loads(r.data.decode('utf-8'))
    return ret


def http_post(url, data, token):
    http = urllib3.PoolManager()
    headers = {'Content-Type': 'application/json', 'token-rxd': token}
    encoded_data = json.dumps(data).encode('utf-8')
    r = http.request('POST', url, body=encoded_data, headers=headers)
    status = json.loads(r.data.decode('utf-8'))['code']
    if status != 200:
        print("HTTP POST FAIL: " + str(json.loads(r.data.decode('utf-8'))))
        return None
    ret = json.loads(r.data.decode('utf-8'))
    return ret


def http_get(url, token):
    http = urllib3.PoolManager()
    if token is None:
        headers = {'Content-Type': 'application/json'}
    else:
        headers = {'Content-Type': 'application/json', 'token-rxd': token}
    r = http.request('GET', url, headers=headers)

    data = r.data.decode('utf-8')
    start = data.find('{')
    end = data.rfind('}')

    if start != -1 and end != -1 and start <= end:
        substring = data[start:end + 1]  # 包含 '}'，所以 end+1
        return json.loads(substring)
    else:
        print("未找到匹配的花括号")
        return None

